<?php

namespace app\admin\service\auth;

use tmcore\base\BaseService;
use app\common\model\auth\AdminRole;
use app\common\cache\AdminAuthCache;
use app\common\model\auth\SystemRole;
use app\common\model\auth\SystemRoleMenu;

/**
 * 角色服务类
 */
class RoleService extends BaseService
{
    /**
     * 获取角色列表
     * @return array
     */
    public static function getList(): array
    {
        // 搜索条件
        $searchParam = [
            '%like%' => ['name'],
            '=' => ['disable']
        ];
        $where = self::getSearchData($searchParam);

        // 返回分页数据
        $list = SystemRole::page($where, self::getPageData(),
            'id,name,desc,sort,disable,create_time',
            ['sort' => 'desc', 'id' => 'desc'],
            ['disable_desc'],
            ['role_menu_index']
        );

        foreach ($list['list'] as &$item) {
            //使用角色的人数
            $item['num'] = AdminRole::where('role_id', $item['id'])->count();
            $menuId = array_column(($item['role_menu_index']), 'menu_id');
            $item['menu_id'] = $menuId;
            unset($item['role_menu_index']);
        }

        return $list;
    }

    /**
     * 添加角色
     * @param array $params
     * @return bool
     */
    public static function add(array $params): bool
    {
        self::beginTrans();
        try {
            $menuId = $params['menu_id'] ?? [];

            $role = SystemRole::create([
                'name' => $params['name'],
                'desc' => $params['desc'] ?? '',
                'sort' => $params['sort'] ?? 0,
                'disable' => $params['disable'] ?? 0,
            ]);

            $data = [];
            foreach ($menuId as $item) {
                if (empty($item)) {
                    continue;
                }
                $data[] = [
                    'role_id' => $role['id'],
                    'menu_id' => $item,
                ];
            }
            (new SystemRoleMenu)->insertAll($data);

            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }


    /**
     * 编辑角色
     * @param array $params
     * @return bool
     */
    public static function edit(array $params): bool
    {
        self::beginTrans();
        try {
            $menuId = $params['menu_id'] ?? [];

            SystemRole::update([
                'id' => $params['id'],
                'name' => $params['name'],
                'desc' => $params['desc'] ?? '',
                'sort' => $params['sort'] ?? 0,
                'disable' => $params['disable'] ?? 0,
            ]);

            if (!empty($menuId)) {
                SystemRoleMenu::where(['role_id' => $params['id']])->delete();
                $data = [];
                foreach ($menuId as $item) {
                    $data[] = [
                        'role_id' => $params['id'],
                        'menu_id' => $item,
                    ];
                }
                (new SystemRoleMenu)->insertAll($data);
            }

            (new AdminAuthCache())->deleteTag();

            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 删除角色
     * @param int $id
     * @return bool
     */
    public static function delete(int $id)
    {
        self::beginTrans();
        try {
            $res = SystemRole::del($id);
            if(!$res) throw new \Exception('删除角色失败');

            if(SystemRoleMenu::where(['role_id' => $id])->count()) {
                $res = SystemRoleMenu::where(['role_id' => $id])->delete();
                if(!$res) throw new \Exception('删除角色关联菜单失败');
            }

            (new AdminAuthCache())->deleteTag();

            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }


    /**
     * 角色详情
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail(int $id): array
    {
        $detail = SystemRole::field('id,name,desc,sort,disable')->find($id);
        $authList = $detail->roleMenuIndex()->select()->toArray();
        $menuId = array_column($authList, 'menu_id');
        $detail['menu_id'] = $menuId;
        return $detail->toArray();
    }


    /**
     * 角色数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAllData()
    {
        return SystemRole::order(['sort' => 'desc', 'id' => 'desc'])
            ->select()
            ->toArray();
    }


}